package top.goldenyear.porpoise.infra.storage.core.service.db;

import java.time.Duration;
import java.util.Collection;
import org.noear.solon.Solon;
import top.goldenyear.porpoise.common.core.model.Ret;
import top.goldenyear.porpoise.infra.storage.config.FileConfig;
import top.goldenyear.porpoise.infra.storage.core.model.Media;
import top.goldenyear.porpoise.infra.storage.core.service.FileClient;
import top.goldenyear.porpoise.infra.storage.core.service.exception.PorpoiseFileException;

public class DbFileClient implements FileClient {
  private final String configId;
  private final FileConfig fileConfig;
  private DbFileService dbFileService;

  public DbFileClient(String configId, FileConfig fileConfig) {
    this.configId = configId;
    this.fileConfig = fileConfig;
    dbFileService = getDbFileService(configId, fileConfig);
  }

  @Override
  public String getConfigId() {
    return configId;
  }

  @Override
  public boolean exists(String bucket, String key) throws PorpoiseFileException {
    return dbFileService.exists(configId, bucket, key);
  }

  @Override
  public String getTempUrl(String bucket, String key, Duration duration) throws PorpoiseFileException, UnsupportedOperationException {
    throw new UnsupportedOperationException();
  }

  @Override
  public Media get(String bucket, String key) throws PorpoiseFileException {
    return dbFileService.get(configId, bucket, key);
  }

  @Override
  public Ret put(String bucket, String key, Media media) throws PorpoiseFileException {
    return dbFileService.put(configId, bucket, key, media);
  }

  @Override
  public Ret delete(String bucket, String key) throws PorpoiseFileException {
    return dbFileService.delete(configId, bucket, key);
  }

  @Override
  public Ret deleteBatch(String bucket, Collection<String> keys) throws PorpoiseFileException {
    return dbFileService.deleteBatch(configId, bucket, keys);
  }

  private DbFileService getDbFileService(String configId, FileConfig fileConfig) {
    if (dbFileService == null) {
      // 是否不需要配置？存储数据库与当前 DbFileService 的数据库一致，不需要，也不允许切换？
      dbFileService = Solon.context().getBean(DbFileService.class);
      dbFileService.setFileConfg(fileConfig);
    }

    return dbFileService;
  }
}
